package org.zhadoop.stream.cql.hooks;

import org.zhadoop.stream.cql.CQLUtils;
import org.zhadoop.stream.cql.DriverContext;
import org.zhadoop.stream.cql.builder.BuilderUtils;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.ExplainStatementContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.LoadStatementContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.ParseContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.SubmitApplicationContext;

/**
 * 在driver 的run 方法执行前后进行一些clean 操作
 * 
 * @author zwd
 *
 */
public class DriverCleanerHook implements DriverRunHook {

	@Override
	public void preDriverRun(DriverContext context, ParseContext parseContext) {
		context.setQueryResult(null);
		if(isLoad(parseContext)){
			context.clean();
		}
		if(CQLUtils.isChangebleCommond(parseContext)){
			context.cleanApp();
		}
	}

	@Override
	public void postDriverRun(DriverContext context, ParseContext parseContext) {
		if(isSubmit(parseContext)){
			context.clean();
		}
		if(isExplain(parseContext)){
			/**
			 * 重置算子名称计数器
			 */
			DriverContext.getBuilderNameSpace().remove();
			DriverContext.getBuilderNameSpace().set(new BuilderUtils());
			
		}
	}
	
	private boolean isSubmit(ParseContext parseContext){
		return parseContext instanceof SubmitApplicationContext;
	}
	
	private boolean isLoad(ParseContext parseContext){
		return parseContext instanceof LoadStatementContext;
	}
	
	private boolean isExplain(ParseContext parseContext){
		return parseContext instanceof ExplainStatementContext;
	}

}
